<?php

namespace Modules\ShopAdmin\Models;
use Illuminate\Support\Facades\DB;
use Modules\AuthAdmin\Services\QueryService;
use Modules\AuthAdmin\Services\CommonService;
use Modules\AuthAdmin\Models\AuthImage as AuthImageModel;
use Modules\ShopAdmin\Models\ShopOrder as ShopOrderModel;
class ShopOrderComplain extends BaseApiModel
{
	/**
     * @name  获取申诉状态列表
     */
	private function status_list(){
		return [
			'0'=>'申诉中',
			'1'=>'通过',
			'2'=>'驳回'
		];
	}
	/**
	 * @name  申诉记录
	 * @param  data array 查询参数
	 * @return  JSON
	 */
    public function order_complain_list($data)
    {
		$model = $this->query();
		$model = (new QueryService())->query_condition($model,$data);
        $list = $model->select('id','content','return_content','images','status','created_at','updated_at')
				->orderBy('id','desc') 
				->where(['order_id'=>$data['id']])
				->paginate($data['pagesize'])
				->toArray();
		$status_list = $this->status_list();
		$http = (new CommonService())->get_http_type();	
		foreach($list['data'] as $k=>$v){
			$list['data'][$k]['status_name'] = $status_list[$v['status']];
			if($v['images']){
				$list['data'][$k]['images'] = AuthImageModel::whereIn('id',explode('|',$v['images']))->select('id','url','open')->get();	
				if($list['data'][$k]['images']){
					$list['data'][$k]['images'] = $list['data'][$k]['images']->toArray();
					foreach($list['data'][$k]['images'] as $k1=>$v1){
						if($v1['open'] == 1){
							$list['data'][$k]['images'][$k1] = $http . $v1['url'];
						}else{
							$list['data'][$k]['images'][$k1] = $v1['url'];
						}
					}
				}else{
					$list['data'][$k]['images'] = [];
				}
			}else{
				$list['data'][$k]['images'] = [];
			}
		}		
		return $this->api_success(['data'=>[
			'list'=>$list['data'],
			'total'=>$list['total']
		]]);
    }
	/**
	 * @name   通过/驳回
	 * @param  data array 申诉数据	
	 * @return  JSON
	 */
	public function order_complain($data){
		$info = $this->select('id','status','order_id')->find($data['id']);
		if($info['status']!=0){
			return $this->api_error();
		}
		DB::beginTransaction();
		try{
			$this->where(['id'=>$info['id']])->update([
				'return_content'=>$data['return_content'],
				'updated_at'=>date('Y-m-d H:i:s'),
				'status'=>$data['status']
			]);
			if(ShopOrderModel::where(['id'=>$info['order_id']])->value('status')==6){
				ShopOrderModel::where(['id'=>$info['order_id']])->update([
					'status'=>($data['status']==1)?8:7
				]);
			}
			DB::commit();
		}catch(\Exception $e){
			DB::rollBack();
			return $this->api_error();
		}
		return $this->api_success();
	}
}
